var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var log4js = require('log4js')
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session')
var ejs = require('ejs')
var fs = require('fs')
var http = require('http')
var socket = require('socket.io')

var routes = require('./routes/index');

var app = express();

var server = http.Server(app)
var io = socket(server)

require('./socket/socket')(io)

process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err)
});

//  日志管理
log4js.configure({
    appenders: [{
            type: 'console'
        }, //控制台输出
        {
            type: 'file',
            filename: 'logs/debug.log',
            maxLogSize: 10240,
            backups: 4,
            category: 'normal'
        }
    ]
});
var logger = log4js.getLogger('normal')
logger.setLevel('INFO')


app.use(log4js.connectLogger(logger, {
    level: log4js.levels.INFO,
    format: ':method :url :status'
}));



app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

var sessionId = Math.random().toString(16).slice(2)
app.use(cookieParser(sessionId));
app.use(session({
    secret: sessionId, //与cookieParser中的一致
    resave: true,
    saveUninitialized: true
}))
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'data')));

app.use('/', express.static(path.resolve(__dirname, 'views')))
app.use('/test', express.static(path.resolve(__dirname, 'views/test')))
app.use('/post', express.static(path.resolve(__dirname, 'views/post')))
app.use('/user', express.static(path.resolve(__dirname, 'views/user')))
app.use('/resource', express.static(path.resolve(__dirname, 'views/resource')))

// view engine setup
app.set('views', [
    path.resolve(__dirname, 'views'),
    path.resolve(__dirname, 'views/test'),
    path.resolve(__dirname, 'views/post'),
    path.resolve(__dirname, 'views/user'),
    path.resolve(__dirname, 'views/resource')
])
app.engine('html', ejs.renderFile)
app.set('view engine', 'html');


app.use('/', routes);

server.listen(8088, function() {
    console.log('project run in 8088 port')
})


module.exports = app;